#include <mysql/mysql.h>
#include <iostream>

int main()
{
    //初始化
    MYSQL* my = mysql_init(nullptr);
    if(!my)
    {
        std::cout<<"初始化失败"<<std::endl;
        return 1;
    }
    const std::string host = "1.94.214.183";
    const std::string user = "wmz";
    const std::string passwd = "wmz123456789.";
    const std::string db = "db1";
    unsigned int port = 3306;

    if(mysql_real_connect(my,host.c_str(),user.c_str(),passwd.c_str(),db.c_str(),port,nullptr,0) == nullptr)
    {
        std::cout<<"连接失败"<<std::endl;
        mysql_close(my);
        return 2;
    }
    std::cout<<"连接成功"<<std::endl;
    //增
    //const std::string sql = "insert into account (name) values ('Tom');";
    //删
    //const std::string sql = "delete from account where name='Tom';";
    //改
    //const std::string sql = "update account set name='王八' where name='田七';";
    //查
    const std::string sql = "select * from account;";
    int n = mysql_query(my,sql.c_str());
    if(n!=0)
    {
        std::cout<<"操作失败"<<std::endl;
        return 3;
    }
    std::cout<<sql<<" success"<<std::endl;

    //查询处理的细节
    //转储  将查询的结果放到一个结果集中
    MYSQL_RES* res = mysql_store_result(my);
    int rows = mysql_num_rows(res);
    int fields = mysql_num_fields(res);
    std::cout<<"行："<<rows<<std::endl;
    std::cout<<"列："<<fields<<std::endl;
    
    //遍历结果集中列名称
    MYSQL_FIELD* field = mysql_fetch_fields(res);
    for(int i = 0;i<fields;i++)
    {
        std::cout<<field[i].name;
    }
    std::cout<<std::endl;
    //遍历结果集的行信息
    for(int i = 0;i<rows;i++)
    {
        MYSQL_ROW result =  mysql_fetch_row(res);
        for(int j = 0;j<fields;j++)
        {
            std::cout<<result[j];
        }
        std::cout<<std::endl;
    }
    //关闭数据库
    mysql_close(my);
    //std::cout<<"获得用户版本"<<mysql_get_client_info()<<std::endl;
    return 0;
}